package com.springboot.jdk.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: zr
 * @date: 2021-09-30
 */
public class ReentrantLockDemo {

    public static volatile int i = 0;

    private static ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                for (int j = 0; j < 10; j++) {
                    // lock.lock();
                    try {
                        lock.tryLock(10, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    i++;
                    System.out.println(i);
                    lock.unlock();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                for (int j = 0; j < 10; j++) {
                    lock.lock();
                    i++;
                    System.out.println(i);
                    lock.unlock();
                }
            }
        }.start();
    }
}
